package ch.unisi.inf.gui.action;

import ch.unisi.inf.viewer.MainImgViewerPanel;

import java.awt.*;
import javax.swing.*;
import java.awt.print.*;

/**
 * @author bejarj@lu.unisi.ch
 */

public class PrintUtilities implements Printable {
	
	private MainImgViewerPanel thumbPanel;
	
	public PrintUtilities(MainImgViewerPanel thumbPanel) {
		this.thumbPanel = thumbPanel;
	}

	public static void printComponent(MainImgViewerPanel thumbPanel){
		new PrintUtilities(thumbPanel).print();
	}
	
	public void print(){
		PrinterJob printJob = PrinterJob.getPrinterJob();
		printJob.setPrintable(this);
		if (printJob.printDialog())
			System.out.println( "Print Test 3");
		      try {
		        printJob.print();
		      } catch(PrinterException pe) {
		        System.out.println("Error printing: " + pe);
		      }
	}

	public int print(Graphics g, PageFormat pageFormat, int pageIndex)
			throws PrinterException {
		if (pageIndex > 0) {
		      return(NO_SUCH_PAGE);
		    } else {
		      Graphics2D g2d = (Graphics2D)g ;
		      g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
		      disableDoubleBuffering(thumbPanel);
		      thumbPanel.paint(g2d);
		      disableDoubleBuffering(thumbPanel);
				System.out.println( "Print Test 4");
		      return(PAGE_EXISTS);
		    }
	}

	private void disableDoubleBuffering(MainImgViewerPanel thumbPanel) {
		RepaintManager currentManager = RepaintManager.currentManager(thumbPanel);
	    currentManager.setDoubleBufferingEnabled(false);	
		System.out.println( "Print Test 5");
	}

	public static void enableDoubleBuffering(MainImgViewerPanel thumbPanel) {
	    RepaintManager currentManager = RepaintManager.currentManager(thumbPanel);
	    currentManager.setDoubleBufferingEnabled(true);
		System.out.println( "Print Test 6");
	  }
	
}
